import { defineStore } from "pinia";
import { ref } from "vue";
import { GetHosts } from "~/api/cmdb";

const useHost = defineStore("host", () => {
  const hostsList = ref([]);
  const hostTree = ref([]);
  const IsHostEmpty = ref(false);
  // 获取用户列表
  const initHostsList = async () => {
    try {
      const res = await GetHosts();
      if (res) {
        hostsList.value = res;
        // 返回是否主机列表为空
        IsHostEmpty.value = hostsList.value.length === 0;
      }
    } catch (error) {}
  };

  const initHostTree = async () => {
    // 获取用户列表
    try {
      const res = await GetHosts();
      if (res) {
        hostTree.value = buildHostTree(res);
        IsHostEmpty.value = hostTree.value.length === 0;
      }
    } catch (error) {}
  };

  const buildHostTree = (hosts) => {
    const hostsObj = {};
    hosts &&
      hosts.forEach((item) => {
        item.onlyId = "name:" + item.name + "addr:" + item.address;
        item.description = `${item.name}-${item.address}`;
        if (Object.prototype.hasOwnProperty.call(hostsObj, item.groupName)) {
          hostsObj[item.groupName].push(item);
        } else {
          Object.assign(hostsObj, { [item.groupName]: [item] });
        }
      });
    const hostTree = [];
    for (const key in hostsObj) {
      const treeNode = {
        ID: key,
        description: key,
        children: hostsObj[key],
      };
      hostTree.push(treeNode);
    }
    return hostTree;
  };
  const init = () => {
    initHostsList();
    initHostTree();
  };

  return {
    init,
    initHostsList,
    initHostTree,
    hostsList,
    hostTree,
    IsHostEmpty,
  };
});

export default useHost;
